package com.gdth.service;

import java.util.ArrayList;
import java.util.List;

import com.gdth.bank.BankApplication;
import com.gdth.bank.bean.TbxxbBean;
import com.gdth.bank.model.TAppTokenModel;
import com.gdth.service.listener.ServiceListener;
import com.gdth.thread.DownLoadThread;
import com.gdth.thread.SynchronizeThread;
import com.gdth.utils.DateTimeUtil;
import com.gdth.utils.GsonUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

public class HeartService extends Service{
	private static final String TAG = "HeartService";

	private final static int longtime = 60 * 1000;
	
    private int count = 0;

	/**
	 * 发送的广播只会在自己App内传播，不会泄露给其他App，确保隐私数据不会泄露
	 * 其他App也无法向你的App发送该广播，不用担心其他App会来搞破坏
	 * 比系统全局广播更加高效
	 */
	private LocalBroadcastManager mLocalBroadcastManager;
	private LocalBroadcastReceiver mLocalBroadcastReceiver;
	
	@Override
	public void onCreate() {
		super.onCreate();
		
        startAlarm();
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	@Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub

        super.onStart(intent, startId);
        
    }
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		init();
		
		count += 1;
		
		start();
		
        return super.onStartCommand(intent, flags, startId);
	}
	
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
    	
    	stopAlarm();

        mMyServiceListener.release();
        
        super.onDestroy();
    }
    
    /**
     * 初始化
     */
    private void init(){
    	if (count == 0) {
    		BankApplication.mInstance.pushNotificationText("服务启动");
			HeartServer.getInstance().setServiceListener(mMyServiceListener);
			
	        initService();
    	}
    }
    
    /**
     * 初始化本地广播
     */
    public void initService(){
    	if (mLocalBroadcastManager == null) {
    		mLocalBroadcastReceiver = new LocalBroadcastReceiver();
    		
    		mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
    		mLocalBroadcastManager.registerReceiver(mLocalBroadcastReceiver, getIntentFilter());
    	}
    	
	}

    /**
	 * 启动
	 */
	private void startAlarm() {
		AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
		long firstime = SystemClock.elapsedRealtime();
		Intent intent = new Intent(this, HeartReceiver.class);
		PendingIntent pi_heart = PendingIntent.getBroadcast(this, 0, intent, 0);
		manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime, longtime, pi_heart);
	}
	
	/**
	 * 停止
	 */
	private void stopAlarm() {
		Intent intent = new Intent(this, HeartReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        //获取闹钟管理器
        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);
	}
    
	SynchronizeThread thread = new SynchronizeThread();
    
	private void start() {
//		startHeart();
//		new Thread(networdThread).start();
		
		if(!thread.isAlive()) {
			if (thread != null) {
				thread = new SynchronizeThread();
			}
			thread.start();
		}
	}
	
    /**
     * 启动一个心跳包
     */
    private void startHeart() {
		HeartServer.getInstance().setHost(BankApplication.mInstance.ip);
		HeartServer.getInstance().setPorts(BankApplication.mInstance.port);

		String token = BankApplication.mInstance.token;
		String deviceid = BankApplication.mInstance.getDeviceByShare();
//		String deviceid = BankApplication.mInstance.getDeviceId();
		HeartServer.getInstance().setToken(token);
		HeartServer.getInstance().setDeviceId(deviceid);
		HeartServer.getInstance().start();
    }
	
	/**
	 * 本地广播
	 * @author arvin
	 *
	 */
	class LocalBroadcastReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO 接收广播
			String action = intent.getAction();
			if (action.equals(BaseAction.action_heart)) {
				
	        } else if (action.equals(BaseAction.LOCATION_ACTION)){
//		        String locationInfo = intent.getStringExtra(BaseAction.LOCATION);
//	        	startHeart();
//        	new Thread(networdThread).start();
			} else if (action.equals(BaseAction.action_heart_timeout)) {
//				BankApplication.getApp().finishAll();
			} else if (action.equals(BaseAction.action_message)) {
				String message = intent.getStringExtra("message");
				getTbxxbList(message);
			}
		}
	}
	
	private void getTbxxbList(String json) {
		JsonArray array = GsonUtil.getJsonArray(json);
		if (array == null || array.size() == 0)
			return;
		List<TbxxbBean> mList = new ArrayList<TbxxbBean>();
		Gson mGson = GsonUtil.getGson();
		for (JsonElement ele : array) {
			TbxxbBean bean = mGson.fromJson(ele, TbxxbBean.class);
			
			mList.add(bean);
		}
		if (mList.size() > 0) {
			DownLoadThread.getInstance().DownLoadByBeans(mList);
		}
	}
	Runnable networdThread = new  Runnable(){
		public void run() {
			startHeart();
		}
	};
	private IntentFilter getIntentFilter(){
		IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(BaseAction.action_heart);
        mIntentFilter.addAction(BaseAction.action_message);
        mIntentFilter.addAction(BaseAction.LOCATION_ACTION);
        mIntentFilter.addAction(BaseAction.action_heart_token);
        mIntentFilter.addAction(BaseAction.action_heart_timeout);
        
        return mIntentFilter;
	}

	private myServiceListener mMyServiceListener = new myServiceListener();
	
	class myServiceListener implements ServiceListener {

		@Override
		public void release() {
			// TODO Auto-generated method stub
//			if (mNotificationManager != null)
//				mNotificationManager.cancel(messageNotificationID);
		}

		@Override
		public void sendBroadcastByLocal(String action) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(action);
			sendBroadcastByLocal(intent);
		}

		@Override
		public void sendBroadcastByLocal(Intent intent) {
			// TODO Auto-generated method stub
			mLocalBroadcastManager.sendBroadcast(intent);
		}

		@Override
		public void pushNotificationText(String val) {
			// TODO Auto-generated method stub
			BankApplication.mInstance.pushNotificationText(val);
		}
		
	}
	
}

